package com.gdth.bank.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;

//import com.gdth.bank.BNDemoGuideActivity;
import com.gdth.bank.R;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.utils.LogUtils;
import com.gdth.bank.widget.BankEditText;
import com.gdth.bank.widget.baiduMap.BaseMapActivity;
import com.gdth.bank.widget.baiduMap.LocationBean;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.utils.PermissionUtil;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.dialog.DialogLoader;

/** 
 * @author  Arvin: 
 * @version 2016年6月13日 上午9:57:35 
 * 
 */
public class BaiduMapActivityTwo extends BaseMapActivity{
	
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
	@ViewInject(id=R.id.header_btn_right, click="onReturnClick") TextView txt_header_right;
	@ViewInject(id=R.id.map_start) BankEditText txt_start;
//	@ViewInject(id=R.id.map_end) BankEditText txt_end;
	@ViewInject(id=R.id.dzcpkhxx_query, click="queryClick") TextView txt_query;
	@ViewInject(id=R.id.khwz) TextView txt_khwz;
    @ViewInject(id=R.id.dzcp_editTextNote) EditText txt_end;
	@ViewInject(id=R.id.map_btn_drive, click="onDriveClickListener") TextView drive;
	@ViewInject(id=R.id.map_btn_transit, click="onTransitClickListener") TextView transit;
	@ViewInject(id=R.id.map_btn_walk, click="onWalkClickListener") TextView walk;
	@ViewInject(id=R.id.map_btn_daohang, click="daohang") Button btn_daohang;
	@ViewInject(id=R.id.map_list) ListView list_map;
	double Latitude;
	double Longitude;
	double LatitudeJd;
	double LongitudeWd;
	LatLng point,point1;
	/** 提示框 */
    public DialogLoader mDialogLoader;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
//        SDKInitializer.initialize(getApplicationContext());
		
		setContentView(R.layout.activity_baidu_map);
		 boolean isAvailable=isNetworkConnected(this);
		 if(!isAvailable) {
			 showDialog(getResources().getString(R.string.param40));
	      }
//		mDialogLoader = new DialogLoader(this);
//		showProgressDialog("地图初始化中。。。");
		init();
		
		if (!isGPSEnabled()) openGPSSetting();
		
		initViews();
		
		PermissionUtil.checkPermissionLocation(this);
//		initWz();
		
	}
	private AlertDialog.Builder builder;
	/**
     * 提示
     */
    private void showDialog(String content) {

        builder = new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.param41))
                .setMessage(content).setPositiveButton(getResources().getString(R.string.param13), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //ToDo: 你想做的事情
                    	 dialogInterface.dismiss();
                    }
                });
        builder.create().show();
    }
    
    public boolean isNetworkConnected(Context context) {  
	      if (context != null) {  
	          ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
	                  .getSystemService(Context.CONNECTIVITY_SERVICE);  
	         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
	          if (mNetworkInfo != null) {  
	              return mNetworkInfo.isAvailable();  
	          }  
	      }  
	     return false;  
	 }  

	

	
	public void getGeoPointBystr(String str){
		if(str!=null){
			Geocoder gc= new Geocoder(BaiduMapActivityTwo.this,Locale.CHINA);
			List<Address> addressList = null;
			try {
				addressList = gc.getFromLocationName(str, 1);
				if(!addressList.isEmpty()){
					Address address_temp = addressList.get(0);
					LatitudeJd = address_temp.getLatitude();
					LongitudeWd = address_temp.getLongitude();
//					gpGeoPoint = new GeoPoint((int)Latitude, (int)Longitude);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	private void initViews(){
        txt_header_title.setText(getResources().getString(R.string.param42));
        txt_start.setLabel(getResources().getString(R.string.param43));
        txt_start.setImage(null);
        txt_start.setImage(null);
        btn_daohang.setVisibility(View.VISIBLE);
//        txt_end.setLabel("客户位置：");
//        txt_end.setImage(null);
        txt_end.setClickable(true);
       LinearLayout layout = (LinearLayout) findViewById(R.id.bfmap_txt);
       layout.setVisibility(View.GONE);
        //开启定位
        location_model = 101;
        this.StartLocation();

		BNOuterLogUtil.setLogSwitcher(true);
		
//        if (initDirs()) {
//			initNavi();		
//		}
    }
	
	public void onDriveClickListener(View v) {
		RoutePlanOption(1);
	}
	
	public void onTransitClickListener(View v) {
		RoutePlanOption(2);
	}
	
	public void onWalkClickListener(View v) {
		RoutePlanOption(3);
	}
	
	/**
	 * 线路查询
	 * @param type
	 */
	private void RoutePlanOption(int type){
		// TODO Auto-generated method stub
        String editSt = txt_start.getValue().toString();
//        String editEn = txt_end.getValue().toString();
        String editEn = txt_end.getText().toString();
        if (editSt.equals("")) {
        	this.showToastMsg(getResources().getString(R.string.param44));
        	return;
        }
       if (editEn.equals("")) {
        	this.showToastMsg(getResources().getString(R.string.param45));
        	return;
        }
       LocationBean bean = this.getLocationAddress();
		String address = txt_start.getValue().toString();
		if (address.equals("")) {
			BaseToast.getInstance().ShowSystemToast(this, getResources().getString(R.string.param46));
			return;
		}
		
		point1 =new LatLng(bean.getJd(), bean.getWd());
        RoutePlanOption("株洲", "株洲", point1, point, type);
	}
	
	/**
	 * 返回s
	 * @param v
	 */
	public void onReturnClick(View v){
		Intent intent = new Intent();
		LocationBean bean = this.getLocationAddress();
		String address = txt_start.getValue().toString();
		if (address.equals("")) {
			BaseToast.getInstance().ShowSystemToast(this, getResources().getString(R.string.param47));
			return;
		}
		intent.putExtra("address", address);
		intent.putExtra("jd", bean.getJd());
		intent.putExtra("wd", bean.getWd());
		this.setResult(AppUtil.activity_map_resultcode, intent);
		this.finish();
	}
	
	public void finishClick(View v){
		finish();
	}
	
	/**
	 * 导航事件
	 * @param arg0
	 */
	public void daohang(View arg0){
//		if (BaiduNaviManager.isNaviInited()) {
//			routeplanToNavi(CoordinateType.GCJ02);
//		}


		
	}
	
	
	/**
	 * 检查GPS是否开启
	 * @return
	 */
	public boolean isGPSEnabled(){
		LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);  
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
	}
	
	/**
	 * 打开gps设置界面
	 */
	public void openGPSSetting(){
		Intent intent = new Intent();  
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
        try{  
            this.startActivity(intent);  
        } catch(ActivityNotFoundException ex)   {  
            intent.setAction(Settings.ACTION_SETTINGS);  
            try {  
                this.startActivity(intent);  
            } catch (Exception e) {  
            }  
        }  
	}
	
	/********************Activity事件*******************/
	@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
	
	@Override
    protected void onStop(){
		this.onStopLocation();
		super.onStop();
	}
    @Override
    protected void onDestroy(){
    	this.onDestroyMap();
    	super.onDestroy();
    }
    @Override
    protected void onResume(){
    	this.onResumeMap();
    	super.onResume();
    }
    @Override
    protected void onPause(){
    	this.onPauseMap();
    	super.onPause();
    }
	
    /**
     * 定位监听
     */
	@Override
	public void seletedLocaton(BDLocation mBDLocation) {
		// TODO Auto-generated method stub
		locationLatLng = new LatLng(baiduMap.getLocationData().latitude, baiduMap.getLocationData().longitude);
		if(null == mBDLocation.getProvince() && null == mBDLocation.getCity() && null == mBDLocation.getDistrict() && null == mBDLocation.getStreet() && null == mBDLocation.getStreetNumber())
		{
			
			realLatitude =  baiduMap.getLocationData().latitude;
			realLongitude = baiduMap.getLocationData().longitude;
			realAddress = txt_start.getValue().toString();
			//Log.i("_______________", realLatitude + "_________" + realLongitude);
		}else {
			
		String addStr = mBDLocation.getProvince() + mBDLocation.getCity() + mBDLocation.getDistrict() + mBDLocation.getStreet() + mBDLocation.getStreetNumber();
		 
		txt_start.setValue(addStr + mBDLocation.getLocationDescribe());
		
		}
//		hideProgressDialog();
//		txt_start.setValue(mBDLocation.getAddrStr());
		
	}
	
	/**
	 * 弹出提示框
	 */
	public void showToastMsg(final String msg) {
		this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(BaiduMapActivityTwo.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
	}
//
//	/**
//	 * 初始化导航
//	 */
//    private void initNavi() {
//		BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new NaviInitListener() {
//			@Override
//			public void onAuthResult(int status, String msg) {
//			    String authinfo = null;
//
//				if (0 == status) {
//					authinfo = getResources().getString(R.string.param48);
//				} else {
//					authinfo = getResources().getString(R.string.param49) + msg;
//				}
//
//				showToastMsg(authinfo);
//			}
//
//			public void initSuccess() {
//				showToastMsg(getResources().getString(R.string.param50));
//				initSetting();
//			}
//
//			public void initStart() {
//				showToastMsg(getResources().getString(R.string.param51));
//			}
//
//			public void initFailed() {
//				showToastMsg(getResources().getString(R.string.param52));
//			}
//		},  null, ttsHandler, null);
//	}
//
	/**
	 * 内部TTS播报状态回传handler
	 */
//	private Handler ttsHandler = new Handler(new Handler.Callback() {
//
//		@Override
//		public boolean handleMessage(Message msg) {
//			// TODO Auto-generated method stub
//
//			int type = msg.what;
//	        switch (type) {
//	            case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
//	                 showToastMsg("Handler : TTS play start");
//	                break;
//	            }
//	            case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
//	                 showToastMsg("Handler : TTS play end");
//	                break;
//	            }
//	            default :
//	                break;
//	        }
//			return false;
//		}
//	});

    /**
     * 导航
     * @param coType
     */
//	private void routeplanToNavi(CoordinateType coType) {
//		BNRoutePlanNode sNode = null;
//		BNRoutePlanNode eNode = null;
//		switch (coType) {
//			case GCJ02: {
//				sNode = new BNRoutePlanNode(116.30142, 40.05087, "百度大厦", null, coType);
//				eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", null, coType);
//				break;
//			}
//			case WGS84: {
//				sNode = new BNRoutePlanNode(116.300821, 40.050969, "百度大厦", null, coType);
//				eNode = new BNRoutePlanNode(116.397491, 39.908749, "北京天安门", null, coType);
//				break;
//			}
//			case BD09_MC: {
//				sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null, coType);
//				eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null, coType);
//				break;
//			}
//			case BD09LL: {
//				sNode = new BNRoutePlanNode(116.30784537597782, 40.057009624099436, "百度大厦", null, coType);
//				eNode = new BNRoutePlanNode(116.40386525193937, 39.915160800132085, "北京天安门", null, coType);
//				break;
//			}
//			default:
//				;
//			}
//			if (sNode != null && eNode != null) {
//				List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
//				list.add(sNode);
//				list.add(eNode);
//				BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
//			}
//	}

//	public class DemoRoutePlanListener implements RoutePlanListener {
//
//		private BNRoutePlanNode mBNRoutePlanNode = null;
//
//		public DemoRoutePlanListener(BNRoutePlanNode node) {
//			mBNRoutePlanNode = node;
//		}
//
//		@Override
//		public void onJumpToNavigator() {
//			for (Activity ac : activityList) {
//				if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {
//					return;
//				}
//			}
//			Intent intent = new Intent(BaiduMapActivityTwo.this, BNDemoGuideActivity.class);
//			Bundle bundle = new Bundle();
//			bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
//			intent.putExtras(bundle);
//			startActivity(intent);
//		}
//
//		@Override
//		public void onRoutePlanFailed() {
//			// TODO Auto-generated method stub
//			showToastMsg("算路失败");
//		}
//	}
	
//	private void initSetting(){
//	    BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
//	    BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
//	    BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
//        BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
//        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
//	}

	private BNOuterTTSPlayerCallback mTTSCallback = new BNOuterTTSPlayerCallback() {
		@Override
		public void stopTTS() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "stopTTS");
		}

		@Override
		public void resumeTTS() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "resumeTTS");
		}

		@Override
		public void releaseTTSPlayer() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "releaseTTSPlayer");
		}

		@Override
		public int playTTSText(String speech, int bPreempt) {
			// TODO Auto-generated method stub
			//LogUtils.e("test_TTS", "playTTSText" + "_" + speech + "_" + bPreempt);

			return 1;
		}

		@Override
		public void phoneHangUp() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "phoneHangUp");
		}

		@Override
		public void phoneCalling() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "phoneCalling");
		}

		@Override
		public void pauseTTS() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "pauseTTS");
		}

		@Override
		public void initTTSPlayer() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "initTTSPlayer");
		}

		@Override
		public int getTTSState() {
			// TODO Auto-generated method stub
			LogUtils.e("test_TTS", "getTTSState");
			return 1;
		}
	};
	public void queryClick(View arg0){
		RoutePlanOption(1);
		this.onStop();
		baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(point), 600);
//		RoutePlanOption(1);
//		
	}
}

